from flask import Flask, request, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from app.utils import custom_jsonify
from app.middleware import handle_errors
import logging
from logging.handlers import RotatingFileHandler
import os

# 初始化扩展
db = SQLAlchemy()
login_manager = LoginManager()

def create_app():
    app = Flask(__name__, template_folder='../templates', static_folder='../static')
    
    # 配置
    app.config.from_object('app.config.Config')
    
    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    
    # 注册蓝图
    from app.routes.auth import auth_bp
    from app.routes.patient import patient_bp
    from app.routes.doctor import doctor_bp
    from app.routes.ward import ward_bp
    from app.routes.department import department_bp
    from app.routes.case import case_bp
    from app.routes.requesting import requesting_bp
    from app.routes.api import api_bp


    app.register_blueprint(api_bp,url_prefix='/api_v1')
    app.register_blueprint(auth_bp, url_prefix='')
    app.register_blueprint(patient_bp)
    app.register_blueprint(doctor_bp)
    app.register_blueprint(ward_bp)
    app.register_blueprint(department_bp)
    app.register_blueprint(case_bp)
    app.register_blueprint(requesting_bp)

    # 添加错误处理
    handle_errors(app)

    # 配置日志
    if not app.debug:
        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler('logs/hospital.log', maxBytes=10240,
                                         backupCount=10)
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
        ))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info('Hospital startup')

    return app
